/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.config.service.impl;

import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.config.dto.ConfigEndDayQueryDto;
import com.icinfo.cloud.provider.punish.config.dto.ConfigWorkRestDayInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigWorkRestDayInfoMapper;
import com.icinfo.cloud.provider.punish.config.service.IConfigWorkRestDayInfoService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigWorkRestDayInfoVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 描述: 工作/休息日配置信息表 config_work_rest_day_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月28日
 */
@Service
@Slf4j
public class ConfigWorkRestDayInfoServiceImpl extends MyBatisServiceSupport implements IConfigWorkRestDayInfoService {
    @Resource
    private ConfigWorkRestDayInfoMapper configWorkRestDayInfoMapper;

    /**
     * 描述：获取工作/休息日配置信息列表
     *
     * @param queryDto {@link ConfigWorkRestDayInfoQueryDto}
     * @return {@link List<ConfigWorkRestDayInfoVo>}
     * @author xiangyuyu
     * @date 2022-03-28 19:55
     */
    @Override
    public List<ConfigWorkRestDayInfoVo> getConfigWorkRestDayInfoList(ConfigWorkRestDayInfoQueryDto queryDto) {
        List<ConfigWorkRestDayInfoVo> list = configWorkRestDayInfoMapper.selectConfigWorkRestDayInfoList(queryDto);
        return list;
    }

    /**
     * 描述：获取指定时间段结束后的截止日期
     *
     * @param {@link ConfigEndDayQueryDto}
     * @return {@link Result <LocalDate>} 截止日期
     * @author xiangyuyu
     * @date 202203-28 21:20
     */
    @Override
    public LocalDate getPeriodEndDate(ConfigEndDayQueryDto queryDto) {
        String startDate = queryDto.getStartDate();
        if (ObjectUtils.isEmpty(startDate)) {
            throw new BusinessException("未指定起始日期");
        }
        //校验是否是日期格式（包含时分秒时，校验通过）
        LocalDate tmpDate = null;
        try {
            tmpDate = LocalDate.parse(startDate);
        } catch (DateTimeParseException e) {
            log.error("非日期格式：" + startDate);
        }
        if (ObjectUtils.isEmpty(tmpDate)) {
            LocalDateTime tmpTime;
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                tmpTime = LocalDateTime.parse(startDate, formatter);
            } catch (DateTimeParseException e) {
                throw new BusinessException("未指定有效的时间格式:" + startDate + "，示例：1999-12-12");
            }
            tmpDate = tmpTime.toLocalDate();
        }
        startDate = tmpDate.toString();
        String beforeOrAfterSign = queryDto.getBeforeOrAfterSign();
        String type = queryDto.getType();
        Integer dayCount = queryDto.getDayCount();
        boolean isContainStartDay = Constant.STRING_1.equals(queryDto.getIsContainStartDay()) ? true : false;
        ConfigWorkRestDayInfoQueryDto q = new ConfigWorkRestDayInfoQueryDto();
        int tmpCount = dayCount;
        if (!isContainStartDay) {
            dayCount += 1;
        }
        //只用在了after
        q.setCount(dayCount);
        q.setType(type);
        q.setDay(startDate);
        q.setBeforeOrAfterSign(beforeOrAfterSign);
        List<ConfigWorkRestDayInfoVo> list = getConfigWorkRestDayInfoList(q);
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            throw new BusinessException("未获取到工作日休息日对应配置列表数据");
        }
        AtomicBoolean isExists = new AtomicBoolean(false);
        String finalStartDate = startDate;
        list.forEach(e -> {
            String listDay = e.getDay().toString();
            if (listDay.equals(finalStartDate)) {
                isExists.set(true);
                return;
            }
        });
        LocalDate deadLine;
        int size = list.size();
        if (isContainStartDay) {
            if (Constant.STRING_BEFORE.equals(beforeOrAfterSign)) {
                deadLine = list.get(size - tmpCount).getDay();
            } else {
                deadLine = list.get(size - 1).getDay();
            }
        } else {
            if (Constant.STRING_BEFORE.equals(beforeOrAfterSign)) {
                if (isExists.get()) {
                    deadLine = list.get(size - 1 - tmpCount).getDay();
                } else {
                    deadLine = list.get(size - tmpCount).getDay();
                }
            } else {
                if (isExists.get()) {
                    deadLine = list.get(size - 1).getDay();
                } else {
                    deadLine = list.get(size - 2).getDay();
                }
            }
        }
        return deadLine;
    }
}